/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.toools.gwt.wmc.server.company;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import java.util.ArrayList;
import java.util.Collection;
import org.toools.gwt.wmc.client.company.CompanyService;
import org.toools.gwt.wmc.server.dao.ICompanyDAO;
import org.toools.gwt.wmc.jpa.Company;
import org.toools.gwt.wmc.jpa.CompanyPart;
import org.toools.gwt.wmc.server.WMCSession;


/**
 *
 * @author Manuel
 */
public class CompanyServiceImpl extends RemoteServiceServlet implements CompanyService {

    private ICompanyDAO companydao;

    /** Company DAO **/
    public void setCompanydao( ICompanyDAO dao ) {
        this.companydao = dao;
    }
    public ICompanyDAO getCompanydao() {
		return companydao;
	}

    public Company getCompanyByID(Integer id) {
        if( WMCSession.isAdmin( getThreadLocalRequest() ) || companydao.belongsTo( id, WMCSession.getAccountID( getThreadLocalRequest() ) ) )
            return companydao.getCompanyByID(id);
        return null;
    }

    public Collection<Company> getCompanies() {
        if( WMCSession.isAdmin( getThreadLocalRequest() ) )
            return companydao.getCompanies();

        return companydao.getCompanies( WMCSession.getAccountID( getThreadLocalRequest() ) );
    }

    public Company create(Company c) {
        CompanyPart cp = new CompanyPart( "Default Company Part", 0, c );
        Collection<CompanyPart> list = new ArrayList<CompanyPart>();
        list.add( cp );
        c.setCompanyParts( list );
        //check if belongs to account or is admin
        if( WMCSession.isAdmin( getThreadLocalRequest() ) )
            return companydao.create(c);
        else
            return companydao.create(c);
    }

    public Boolean delete(Company c) {
        if( WMCSession.isAdmin( getThreadLocalRequest() ) || companydao.belongsTo( c.getId(), WMCSession.getAccountID( getThreadLocalRequest() ) ) )
            return companydao.delete(c);
        return false;
    }

    public Boolean update(Company c) {
        if( WMCSession.isAdmin( getThreadLocalRequest() ) || companydao.belongsTo( c.getId(), WMCSession.getAccountID( getThreadLocalRequest() ) ) )
            return companydao.update(c);
        return false;
    }

}
